package com.heima.behavior.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.IApReadBehaviorService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dto.BehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements IApReadBehaviorService {

    @Autowired
    public CacheService cacheService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public ResponseResult read(BehaviorDto dto) {
        // 1. 检查参数
        if (dto == null || dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 是否登录
        ApUser apUser = AppThreadLocalUtil.getUser();
        if (apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }


        // 3. 更新阅读次数
        String key = "READ-BEHAVIOR-" + dto.getArticleId().toString();
        String hashKey = apUser.getId().toString();

        String readBehaviorJSON = (String)cacheService.hGet(key, hashKey);
        if (StrUtil.isNotBlank(readBehaviorJSON)){
            BehaviorDto behaviorDto = JSON.parseObject(readBehaviorJSON, BehaviorDto.class);
            dto.setCount(behaviorDto.getCount() + dto.getCount());
        }

        // 保存数据
        log.info("保存数据：{}，{}，{}", key, hashKey, JSON.toJSONString(dto));
        cacheService.hPut(key, hashKey, JSON.toJSONString(dto));

        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setAdd(1);
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));

        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }
}
